package com.vivo.tasks.vivofx;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.vivo.common.DatabaseContextHolder;
import com.vivo.dealer.entity.VivoWarehouse;
import com.vivo.dealer.entity.VivoWares;
import com.vivo.dealer.entity.VivoWaresKind;
import com.vivo.dealer.service.VivoWarehouseService;
import com.vivo.dealer.service.VivoWaresKindService;
import com.vivo.dealer.service.VivoWaresService;
import com.vivo.fx.dealer.entity.FxWarehouseinfo;
import com.vivo.fx.dealer.entity.FxWaresinfo;
import com.vivo.fx.dealer.entity.FxWareskind;
import com.vivo.fx.dealer.service.FxWarehouseinfoService;
import com.vivo.fx.dealer.service.FxWaresinfoService;
import com.vivo.fx.dealer.service.FxWareskindService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class TaskViWare {

    @Autowired
    private FxWaresinfoService fxWaresinfoService;

    @Autowired
    private VivoWaresService vivoWaresService;

    @Autowired
    private FxWarehouseinfoService fxWarehouseinfoService;

    @Autowired
    private VivoWarehouseService vivoWarehouseService;

    @Autowired
    private FxWareskindService fxWareskindService;

    @Autowired
    private VivoWaresKindService vivoWaresKindService;

    public void SyncData() {
        // TODO Update data

//        GetWaresKind("ah");
//
//        GetWaresKind("js");

//        GetWarehouseInfo("ah");
//        GetWarehouseInfo("js");
//
//        GetWaresInfo("ah");
//        GetWaresInfo("js");

        SyncWares();
    }

    /**
     * 同步商品种类信息
     */
    public void SyncWaresKind() {
        GetWaresKind("ah");
        GetWaresKind("js");
    }

    /**
     * 同步商品信息
     */
    public void SyncWares() {
        GetWaresInfo("ah");
        GetWaresInfo("js");

        // 同步手机颜色数据字典
        UpdWaresColorDict();
    }

    /**
     * 同步商品仓库信息
     */
    public void SyncWarehouseinfo() {
        GetWarehouseInfo("ah");
        GetWarehouseInfo("js");
    }


    private void GetWarehouseInfo(String area) {
        System.out.println("get warehouse info data from " + area + " db start...");

        List<FxWarehouseinfo> houseList = null;

        int pageStart = 1;
        int pageSize = 5000;
        Page<FxWarehouseinfo> page = new Page<FxWarehouseinfo>(pageStart, pageSize);
        FxWarehouseinfo fxWarehouseinfo = new FxWarehouseinfo();

        VivoWarehouse vivoWarehouse = new VivoWarehouse();
        vivoWarehouse.setTableZone(area);
        VivoWarehouse lastItem = vivoWarehouseService.getLastItem(vivoWarehouse);

        // 设置当前数据库最新数据
        if (lastItem != null) {
            fxWarehouseinfo.setWarehouseid(lastItem.getWarehouseId());
        }

        try {
            // 切换数据库
            Helper.changeDB(area);

            Page<FxWarehouseinfo> pageRes = fxWarehouseinfoService.findPage(page, fxWarehouseinfo);
            DatabaseContextHolder.setMainDb();

            saveWarehouseinfo(pageRes.getList(), area);

            for (int i = pageStart + 1; i <= pageRes.getTotalPage(); i++) {
                System.out.println("page count is : " + pageRes.getTotalPage() + " page num is " + pageRes.getPageNo());
                page.setPageNo(i);

                Helper.changeDB(area);

                pageRes = fxWarehouseinfoService.findPage(page, fxWarehouseinfo);
                DatabaseContextHolder.setMainDb();

                saveWarehouseinfo(pageRes.getList(), area);
            }
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        System.out.println("get data from " + area + " db end.");
    }

    private void saveWarehouseinfo(List<FxWarehouseinfo> warehouseinfos, String area) {
        for (FxWarehouseinfo fwi: warehouseinfos) {
            VivoWarehouse vwh = new VivoWarehouse();
            vwh.setTableZone(area);
            vwh.setWarehouseId(fwi.getWarehouseid());

            vwh.setName(fwi.getWarehousename());
            vwh.setDealerId(fwi.getWarehousedealerid());
            vwh.setMatDealerId(fwi.getMatdealerid());
            vwh.setCode(fwi.getWarehousecode());
            vwh.setType(fwi.getWarehousetype());
            vwh.setProperty(fwi.getWarehouseproperty());
            vwh.setRemarks(fwi.getRemarks());
            vwh.setDefaultType(fwi.getDefaultwarehousetype());
            vwh.setLevel(fwi.getWarehouselevel());

            try {
                vivoWarehouseService.save(vwh);
            } catch (Exception e) {
                List<VivoWarehouse> list = vivoWarehouseService.findList(vwh);
                if (list.size() > 0) {
                    System.out.println("has existed ..." + vwh.getWarehouseId());
                    continue;
                }
            }
        }
    }


    private void GetWaresInfo(String area) {
        System.out.println("get data from " + area + " db start...");

        int pageStart = 1;
        int pageSize = 5000;
        Page<FxWaresinfo> page = new Page<FxWaresinfo>(pageStart, pageSize);
        FxWaresinfo fxWaresinfo = new FxWaresinfo();

        try {
            // 切换数据库
            Helper.changeDB(area);

            Page<FxWaresinfo> pageRes = fxWaresinfoService.findPage(page, fxWaresinfo);
            DatabaseContextHolder.setMainDb();

            saveWaresInfo(pageRes.getList(), area);

            for (int i = pageStart + 1; i <= pageRes.getTotalPage(); i++) {
                System.out.println("page count is : " + pageRes.getTotalPage() + " page num is " + pageRes.getPageNo());
                page.setPageNo(i);

                Helper.changeDB(area);

                pageRes = fxWaresinfoService.findPage(page, fxWaresinfo);
                DatabaseContextHolder.setMainDb();

                saveWaresInfo(pageRes.getList(), area);
            }
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        System.out.println("get data from " + area + " db end.");
    }


    private void saveWaresInfo(List<FxWaresinfo> waresinfos, String area) {
        VivoWaresKind vwkind = new VivoWaresKind();
        for (FxWaresinfo fwi: waresinfos) {

            VivoWares vw = new VivoWares();
            vw.setTableZone(area);
            vw.setWaresId(fwi.getWaresid());

            vwkind.setId(fwi.getWareskindid());

            vw.setKind(vwkind);

//            vw.setWaresKindId(fwi.getWareskindid());
            vw.setShowOrder(fwi.getShoworder());
            vw.setWaresLevelCode(fwi.getWareslevelcode());
            vw.setWaresCode(fwi.getWarescode());
            vw.setSkuCode(fwi.getSkucode());
            vw.setWaresName(fwi.getWaresname());
            vw.setBaseUnitId(fwi.getBaseunitid());
            vw.setAddionsUnitId(fwi.getAddionsunitid());
            vw.setWaresPropertyId(fwi.getWarespropertyid());
            vw.setWaresState(fwi.getWaresstate());
            vw.setWaresTypeId(fwi.getWarestypeid());

            vw.setIsSnManage(fwi.getIssnmanage());
            vw.setIsBatchManage(fwi.getIsbatchmanage());
            vw.setIsExamine(fwi.getIsexamine());
            vw.setIsCheck(fwi.getIscheck());
            vw.setExpiryDate(fwi.getExpirydate());
            vw.setIsCustomSales(fwi.getIscustomsales());
            vw.setFactoryMaterialCode(fwi.getFactorymaterialcode());

            vw.setWaresColorId(fwi.getWarescolorid());

            try {
                vivoWaresService.save(vw);
            } catch (Exception e) {
                List<VivoWares> wares = vivoWaresService.findList(vw);
                if (wares.size() > 0) {
                    System.out.println("has existed ..." + vw.getWaresId());
                    continue;
                }
            }

        }
    }


    private void GetWaresKind(String area) {
        System.out.println("get data from " + area + " db start...");

        List<FxWareskind> kindList = null;

        try {
            // 切换数据库
            Helper.changeDB(area);

            kindList = fxWareskindService.findList(new FxWareskind());
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        Collections.sort(kindList, new Comparator<FxWareskind>() {
            @Override
            public int compare(FxWareskind o1, FxWareskind o2) {
                return Integer.valueOf(o1.getWareskindcode().length()).compareTo(o2.getWareskindcode().length());
            }
        });

        for (FxWareskind fwk: kindList) {

            VivoWaresKind oldV = vivoWaresKindService.get(fwk.getWareskindid());
            if (oldV != null) {
                System.out.println("has existed!...");
                continue;
            }

            VivoWaresKind vwk = new VivoWaresKind();
            vwk.setIsTaskInsert(true);
            vwk.setId(fwk.getWareskindid());
            vwk.setKind(fwk.getWaresbigkind());
            vwk.setCode(fwk.getWareskindcode());
            vwk.setName(fwk.getWareskindname());
            vwk.setPropertyId(fwk.getPropertyid());

            if (fwk.getParentwareskindid() == null) {
                vwk.setParent(null);
            } else {
                VivoWaresKind praVwk = vivoWaresKindService.get(fwk.getParentwareskindid());
                if (praVwk != null) {
                    vwk.setParent(praVwk);
                } else {
                    vwk.setParent(null);
                }
            }

            try {
                vivoWaresKindService.save(vwk);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        System.out.println("get data from " + area + " db end.");
    }

    @Autowired
    private DictService dictService;

    /**
     * 更新系统中商品颜色的字典数据
     * 更新字典数据保存在FxWaresinfoDao.xml 中，需要对其进行检测
     */
    private void UpdWaresColorDict() {

        String parentDictId = "FB370F09AE634F08A82D75B2B8C672Fr";
        String dictType = "wares_color";
        String dictDesc = "手机颜色";
        List<Dict> dictList = DictUtils.getDictList(dictType);

        Map<String, Dict> dictMap = new HashMap<String, Dict>();
        for (Dict dict: dictList) {
            dictMap.put(dict.getValue(), dict);
        }

        int count = 0;

        // 获取江苏颜色字典
        Helper.changeDB("js");
        List<Dict> jsColorList = fxWaresinfoService.getDictList(parentDictId);

        Helper.changeDB("ah");
        List<Dict> ahColorList = fxWaresinfoService.getDictList(parentDictId);

        DatabaseContextHolder.setMainDb();

        count = saveColorList(jsColorList, dictMap);
        count += saveColorList(ahColorList, dictMap);

        System.out.println("同步颜色字典完毕！共添加" + count + "条！");
    }

    private int saveColorList(List<Dict> colorList, Map<String, Dict> dictMap) {
        String dictType = "wares_color";
        String dictDesc = "手机颜色";

        int count = 0;

        for (Dict dict: colorList) {
//            字典中不存在
            if (dictMap.get(dict.getValue()) == null) {
                dict.setType(dictType);
                dict.setDescription(dictDesc);
                dict.setSort((dictMap.size() + 1 * 10));

                try {
                    dictService.save(dict);
                    dictMap.put(dict.getValue(), dict);
                    count++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return count;
    }
}
